import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:logmanager/utils/string_ext.dart';

import 'base_response.dart';
import 'dio/base_res.dart';
import 'dio/dio_manager.dart';
import 'dio/dio_method.dart';
import 'do_main_config.dart';
import 'http_code.dart';

/// GetConnect网络请求基类封装  使用GetContact通常可以用于网络请求或者通信
/// ?? 左边为null ，则返回右边的值，否则返回左边值

class BaseConnent extends GetConnect {
  @override
  void onInit() {
    httpClient.baseUrl = DoMainConfig.DO_MAIN;
    // httpClient.baseUrl =
    //     "https://www.fastmock.site/mock/d94f8c6b97bf04c9d20760314ceffae7";

    // 请求拦截
    httpClient.addRequestModifier<void>((request) {
      request.headers['Authorization'] = '123345678';
      request.headers['api-version'] = 'v1';
      // debugger(message: request.toString());
      "接口请求：====地址：${request.url}  \n 请求方式：${request.method}".logi();
      return request;
    });

    // 响应拦截
    httpClient.addResponseModifier((request, response) {
      // debugger(message: "=======>$request ------$response");
      // debugger(message: response.toString());
      "接口响应：$response".logi();
      return response;
    });
  }

  @override
  // TODO: implement defaultDecoder
  // Decoder? get defaultDecoder => super.defaultDecoder;
  Decoder<BaseResponse>? get defaultDecoder => (data) {
        try {
          // return BaseResponse.fromJson(data);
          var code = data['code'];
          var baseResponse = BaseResponse(code: code);
          baseResponse.message = data['message'];
          if (code == HttpCode.success) {
            baseResponse.data = data['data'];
          }
          return baseResponse;
        } catch (error) {
          // return BaseResponse(code: HttpCode.serverError, message: '服务端异常');
          print("aabb==============error：$error");
          return BaseResponse(code: HttpCode.serverError);
        }
      };

  netPost(String? url, dynamic body,
      {String? contentType,
      Map<String, String>? headers,
      Map<String, dynamic>? query,
      Progress? uploadProgress,
      success,
      fail,
      showLoading = true, // 默认显示网络加载loading
      loadingMsg = "加载中...", // loading文案
      toastFailMsg = true, // 默认吐司网络请求错误
      baseResponse}) async {
    if (showLoading) {
      EasyLoading.show(status: loadingMsg);
    }
    var res = await post(url, body,
        contentType: "application/x-www-form-urlencoded",
        decoder: defaultDecoder);
    BaseResponse bReasponse = res.body as BaseResponse;
    if (showLoading) {
      EasyLoading.dismiss();
    }

    if (bReasponse.code == HttpCode.success) {
      if (success != null) {
        success(bReasponse.data);
      }
    } else {
      if (fail != null) {
        if (toastFailMsg) {
          bReasponse.message?.toast();
        }
        fail(bReasponse.message);
      } else {
        print("吐司提示");
      }
    }
    if (baseResponse != null) {
      baseResponse(bReasponse);
    }
  }

  requestHttp<T>(String url,
      {DioMethod method = DioMethod.POST,
      Map<String, dynamic>? queryParameters,
      data,
      Map<String, dynamic>? headers,
      Function(T data)? success,
      Function(String errorMsg)? failMsg,
      Function(BaseRes baseResponse)? baseResponse,
      showLoading = false, // 默认显示网络加载loading
      loadingMsg = "加载中...", // loading文案
      toastFailMsg = true, // 默认吐司网络请求错误
      Function(int count, int total)? onSendProgress // 文件上传进度监听，只有Post方式才能回调该函数
      }) async {
    DioManager().request<T>(url,
        method: method,
        queryParameters: queryParameters,
        data: data,
        headers: headers,
        success: success,
        failMsg: failMsg,
        baseResponse: baseResponse,
        showLoading: showLoading,
        onSendProgress: onSendProgress);
  }
}
